<template>
  <div class="pay-choose-page">
    <h2>请选择支付方式</h2>

    <!-- 订单概要 -->
    <div v-if="orderInfo" class="order-info">
      <p v-for="it in orderInfo.items" :key="it.skuId">
        {{ it.skuName }} × {{ it.quantity }}
      </p>
      <p>应付总额：¥{{ Number(orderInfo.payAmount).toFixed(2) }}</p>
    </div>

    <!-- 配送方式 + 地址 -->
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="配送方式" prop="deliveryType">
        <el-radio-group v-model="form.deliveryType">
          <el-radio :label="1">快递到家</el-radio>
          <el-radio :label="2">门店自提</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="收货 / 自提地址" prop="receiverAddr">
        <el-input
          v-model="form.receiverAddr"
          placeholder="请输入详细地址"
          maxlength="120"
          show-word-limit
          clearable
        />
      </el-form-item>
    </el-form>

    <!-- 支付按钮 -->
    <div class="pay-options">
      <el-button type="primary" @click="payByBalance" :loading="loading">
        使用余额支付
      </el-button>
      <el-button type="success" @click="payByAlipay" :loading="loading">
        使用支付宝支付
      </el-button>
    </div>
  </div>
</template>


<script setup>
/* -------------------------------------------------
 * 支付选择页 <script setup>
 * 依赖：Vue 3 · Vue‑Router · Element‑Plus · axios
 * ------------------------------------------------- */

import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getOrderInfo, payWithBalance } from '@/api/pay';
import { rechargeWalletService } from '@/api/pay'
import request from '@/utils/request';

/* ---------- 路由 / 订单参数 ---------- */
const route    = useRoute();
const router   = useRouter();
const orderSn  = route.query.orderSn;

/* ---------- 表单 State ---------- */
const formRef = ref(null);
const form    = ref({
  deliveryType : 1,   // 1=快递 2=自提
  receiverAddr : ''
});
const rules = {
  deliveryType : [{ required: true, message: '请选择配送方式', trigger: 'change' }],
  receiverAddr : [{ required: true, message: '地址不能为空',    trigger: 'blur' }]
};

/* ---------- 订单信息 ---------- */
const orderInfo = ref(null);
const statusLabel = {             // 后端状态枚举
  0: '待付款',
  1: '待发货',
  2: '已发货',
  3: '已完成',
  4: '已取消',
  5: '待退款',
  6: '已退款',
  7: '退款失败'
};

onMounted(async () => {
  try {
    const res = await getOrderInfo(orderSn);
    if (res.data.code === '200') orderInfo.value = res.data.data;
    else                         ElMessage.error(res.data.message || '加载订单信息失败');
  } catch (e) {
    ElMessage.error('网络异常，稍后再试');
  }
});

/* ---------- Loading 控制 ---------- */
const loading = ref(false);

/* ---------- 余额支付 ---------- */
const payByBalance = () => {
  formRef.value.validate(async valid => {
    if (!valid) return;
    const { value: password, action } = await ElMessageBox.prompt(
      '请输入登录密码进行余额支付',
      '余额支付确认',
      { inputType: 'password', confirmButtonText: '确认支付', cancelButtonText: '取消' }
    );
    if (action !== 'confirm') return;

    loading.value = true;
    try {
      const res = await payWithBalance({
        orderSn,
        password,
        deliveryType : form.value.deliveryType,
        receiverAddr : form.value.receiverAddr
      });
      if (res.data.code === '200') {
        ElMessage.success('支付成功');
        router.replace('/index');
      } else {
        ElMessage.error(res.data.message || '支付失败');
      }
    } catch (e) {
      ElMessage.error('请求失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  });
};

/* ---------- 支付宝支付 ---------- */
const payByAlipay = () => {
  formRef.value.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      const res = await request.post(
        '/api/pay/alipay',
        {
          orderSn,
          deliveryType : form.value.deliveryType,
          receiverAddr : form.value.receiverAddr
        },
        { responseType: 'text' }
      );
      const div = document.createElement('div');
      div.innerHTML = res.data;
      document.body.appendChild(div);
      div.querySelector('form')?.submit();
    } catch (e) {
      ElMessage.error('支付宝支付发起失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  });
};
</script>



<style scoped>
.pay-choose-page {
  max-width: 600px;
  margin: 80px auto;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  text-align: center;
}

.order-info {
  margin-bottom: 30px;
  font-size: 16px;
  line-height: 2;
}

.pay-options > .el-button {
  margin: 0 10px;
  width: 200px;
}
</style>
